import pygame
import requests
from pygame.locals import *
import sys, os

pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
BLUE = (0, 120, 215)

# 窗口尺寸
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600

class ClientGUI:
    def __init__(self):
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        pygame.display.set_caption("音乐客户端")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont('simhei', 18)
        self.server_url = "http://localhost:5000"
        
        # GUI组件
        self.components = []
        self.init_ui()
        self.search_results = []
        
    def init_ui(self):
        # 搜索框
        self.search_input = InputBox(20, 20, 560, 40, "搜索歌曲或歌手...")
        self.search_btn = Button(600, 20, 160, 40, "搜索", self.do_search)
        
        # 结果列表
        self.result_list = ListBox(20, 80, 760, 200, [])
        
        # 队列列表
        self.queue_list = ListBox(20, 300, 760, 200, [])
        
        # 控制按钮
        self.add_btn = Button(20, 520, 100, 40, "添加", self.add_selected)
        self.play_btn = Button(140, 520, 100, 40, "播放", self.toggle_play)
        
        self.components.extend([
            self.search_input, self.search_btn,
            self.result_list, self.queue_list,
            self.add_btn, self.play_btn
        ])
        
    def do_search(self):
        query = self.search_input.text
        if query:
            try:
                response = requests.get(f"{self.server_url}/search?q={query}")
                self.search_results = response.json()
                self.result_list.update_items([
                    f"{item['title']} - {item['artist']}" 
                    for item in self.search_results
                ])
            except Exception as e:
                print("搜索失败:", e)

    def add_selected(self):
        selected = self.result_list.selected_index
        if 0 <= selected < len(self.search_results):
            song = self.search_results[selected]
            try:
                requests.post(f"{self.server_url}/add_song", json=song)
                self.refresh_queue()
            except Exception as e:
                print("添加失败:", e)

    def toggle_play(self):
        try:
            requests.post(f"{self.server_url}/playback_control", 
                         json={'command': 'toggle'})
            self.refresh_status()
        except Exception as e:
            print("控制失败:", e)

    def refresh_queue(self):
        try:
            response = requests.get(f"{self.server_url}/get_queue")
            self.queue_list.update_items([
                f"{item['title']} - {item['artist']}" 
                for item in response.json()
            ])
        except Exception as e:
            print("刷新队列失败:", e)

    def run(self):
        running = True
        while running:
            self.screen.fill(WHITE)
            
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                elif event.type == KEYDOWN:
                    self.search_input.handle_input(event)
                elif event.type == MOUSEBUTTONDOWN:
                    for comp in self.components:
                        comp.handle_click(event.pos)
            
            # 绘制组件
            for comp in self.components:
                comp.draw(self.screen)
            
            pygame.display.flip()
            self.clock.tick(30)

        pygame.quit()
        sys.exit()

# 其他组件实现（InputBox等）与服务端类似...
class Button:
    def __init__(self, x, y, w, h, text, callback):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text
        self.callback = callback
        self.color = BLUE

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect)
        font = pygame.font.SysFont('simhei', 16)
        text_surf = font.render(self.text, True, WHITE)
        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)

    def handle_click(self, pos):
        if self.rect.collidepoint(pos):
            self.callback()

class ListBox:
    def __init__(self, x, y, w, h, items):
        self.rect = pygame.Rect(x, y, w, h)
        self.items = items
        self.scroll_offset = 0
        self.item_height = 30

    def update_items(self, new_items):
        self.items = new_items

    def draw(self, surface):
        # 绘制背景
        pygame.draw.rect(surface, WHITE, self.rect)
        pygame.draw.rect(surface, GRAY, self.rect, 2)
        
        # 绘制项目
        visible_items = self.items[self.scroll_offset:self.scroll_offset+15]
        for i, item in enumerate(visible_items):
            y_pos = self.rect.y + 5 + i*self.item_height
            text = f"{i+1+self.scroll_offset}. {item['title']}"
            if item['type'] == 'local':
                text += f" ({os.path.basename(item['path'])})"
            else:
                text += f" ({item['url'][:20]}...)"
            font = pygame.font.SysFont('simhei', 14)
            text_surf = font.render(text, True, BLACK)
            surface.blit(text_surf, (self.rect.x+10, y_pos))

class InputDialog:
    def __init__(self, title, parent_surface):
        self.parent = parent_surface
        self.width = 400
        self.height = 150
        self.rect = pygame.Rect(
            (WINDOW_WIDTH-self.width)//2, 
            (WINDOW_HEIGHT-self.height)//2,
            self.width, self.height
        )
        self.font = pygame.font.SysFont('simhei', 18)
        self.title = title
        self.input_text = ""
        self.active = True

    def run(self):
        input_box = pygame.Rect(self.rect.x+20, self.rect.y+60, 360, 32)
        while True:
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_RETURN:
                        return self.input_text
                    elif event.key == K_BACKSPACE:
                        self.input_text = self.input_text[:-1]
                    else:
                        self.input_text += event.unicode
                elif event.type == MOUSEBUTTONDOWN:
                    if not input_box.collidepoint(event.pos):
                        return None

            # 绘制对话框
            self.parent.fill(BLACK)  # 半透明背景需要额外处理
            pygame.draw.rect(self.parent, WHITE, self.rect)
            
            # 标题
            title_surf = self.font.render(self.title, True, BLACK)
            self.parent.blit(title_surf, (self.rect.x+20, self.rect.y+20))
            
            # 输入框
            pygame.draw.rect(self.parent, GRAY, input_box, 2)
            text_surf = self.font.render(self.input_text, True, BLACK)
            self.parent.blit(text_surf, (input_box.x+5, input_box.y+5))
            
            pygame.display.flip()

if __name__ == '__main__':
    client = ClientGUI()
    client.run()